package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 用户下单
     * @param orders
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}", orders);
        //调用Service层
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 用户下单信息分页查询
     * 需求分析：
     * 根据下单时间降序查询所有订单信息；
     * 如果查询条件有订单号、开始时间和结束时间的话，根据条件查询。
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number, String beginTime, String endTime){
        log.info("page = {}, pageSize = {}, number = {}, beginTime = {}, endTime = {}", page, pageSize, number, beginTime, endTime);

        //1。构造分页构造器
        Page<Orders> pageInfo = new Page<>(page, pageSize);

        //2。构造条件构造器
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        //根据订单号，开始时间和结束时间进行查询
        queryWrapper.like(StringUtils.isNotEmpty(number), Orders::getNumber, number)
                .gt(StringUtils.isNotEmpty(beginTime), Orders::getOrderTime, beginTime) //gt：大于
                .lt(StringUtils.isNotEmpty(endTime), Orders::getOrderTime, endTime); //lt：小于
        //添加排序条件
        queryWrapper.orderByDesc(Orders::getOrderTime);


        //3。分页查询
        orderService.page(pageInfo, queryWrapper);

        return R.success(pageInfo);
    }

    /**
     * 修改订单的派送状态
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> dispatch(@RequestBody Orders orders){ //@Requestbody:需要传入类；前端传过来的数据没有封装成为一个对象，不加它。
        log.info("派送信息：status = {}, id = {}", orders.getStatus(), orders.getId());

        //1。根据订单的id查到订单信息
        Orders order = orderService.getById(orders.getId());
        //2。修改订单的状态并保存到数据库
        order.setStatus(orders.getStatus());
        orderService.updateById(order);

        return R.success("操作成功！");
    }

    /**
     * 移动端用户查看自己订单分页查询
     * 需求分析：
     * 不仅需要分页查询订单信息，还要查询订单细节信息，需要使用OrdersDto
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> page(int page, int pageSize){
        log.info("订单分页查询：page = {}, pageSize = {}", page, pageSize);

        //1。构建一个分页查询，查出订单的分页数据
        Page<Orders> OrdersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId, BaseContext.getCurrentId());
        queryWrapper.orderByDesc(Orders::getOrderTime);
        orderService.page(OrdersPage, queryWrapper);

        //2。这里还需要订单细节信息，因此再构建一个OrdersDto的分页查询
        Page<OrdersDto> ordersDtoPage = new Page<>();
        //除了records属性的信息全部拷贝过来
        BeanUtils.copyProperties(OrdersPage, ordersDtoPage, "records");

        //3。从订单的分页数据拿出records属性，进行遍历修改，并赋值被一个新的集合作为OrdersDto的分页查询的records属性
        List<Orders> records = OrdersPage.getRecords();
        List<OrdersDto> list =  records.stream().map((item) -> {
            //为每个ordersDto设置订单细节信息，这样ordersDto不仅包含订单信息还包含了订单细节信息
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(item, ordersDto);
            List<OrderDetail> orderDetailList = getOrderDetailListByOrderId(item.getId());
            if (orderDetailList != null){
                ordersDto.setOrderDetails(orderDetailList);
            }
            return ordersDto;
        }).collect(Collectors.toList());
        ordersDtoPage.setRecords(list);

        return R.success(ordersDtoPage);
    }

    //提取一个方法：根据订单id查询订单细节
    public List<OrderDetail> getOrderDetailListByOrderId(Long orderId){
        LambdaQueryWrapper<OrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId, orderId);
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper);
        return orderDetailList;
    }

    /**
     * 移动端再来一段功能
     * 需求分析：
     * 需要先清空原来的购物车信息，再把这个订单的订单细节放到购物车中
     * @param orders
     * @return
     */
    @PostMapping("/again")
    public R<String> again(@RequestBody Orders orders){
        Long ordersId = orders.getId();
        log.info("需要再来一单的订单id为：{}", ordersId);

        //1。清空当前用户的购物车
        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, currentId);
        shoppingCartService.remove(queryWrapper);

        //2。根据订单的id查出所有的订单细节
        LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(OrderDetail::getOrderId, ordersId);
        List<OrderDetail> orderDetailList = orderDetailService.list(queryWrapper1);

        //3。根据订单细节获取数据放到新建的购物车中
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map((item) -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(currentId);
            shoppingCart.setImage(item.getImage());
            Long dishId = item.getDishId();
            Long setmealId = item.getSetmealId();
            if (dishId != null) {
                //如果是菜品那就添加菜品的查询条件
                shoppingCart.setDishId(dishId);
            } else {
                //添加到购物车的是套餐
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setName(item.getName());
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        //4。保存新的购物车信息
        shoppingCartService.saveBatch(shoppingCartList);

        return R.success("再来一单操作成功！");
    }

}
